{% extends "base.html" %}
{% load custom_tag %}
{% block title %}
    机柜管理
{% endblock %}

{% block status %}
    机柜信息
{% endblock %}

{% block breadcrumb %}
    <ol class="breadcrumb">
        <li><a href="/"><i class="fa fa-home"></i> Home</a></li>
        <li class="active">机柜管理</li>
    </ol>
{% endblock %}

{% block content %}
    <div class="row">
        <div href="#" class="col-lg-12" style="margin: 0 20px 10px 0;font-size: 12px">
            <input type="text" size="30" placeholder="搜索" style="height: 30px">
            <select onchange="ChangeType(this)" id="idc-search" style="height: 30px;width: 150px">
                <option value="">以 机房</option>
                <option disabled>----------</option>
                {% for idc in idc_list %}
                    <option value="{{ idc.id }}">{{ idc.name }}</option>
                {% endfor %}
            </select>
            <button class="btn btn-inline btn-success" style="height: 30px;font-size: 12px">搜索</button>
            <a href="/assets/cabinet_add/" class="pull-right">
                <i class="glyphicon glyphicon-plus"></i>增加机柜
            </a>
        </div>
        <div class="col-lg-12">
            <div class="panel panel-default">
                <div class="panel-body">
                    <table width="100%" class="table table-striped table-hover" id="dataTables-example">
                        <thead>
                            <tr style="color: white;background: #6f7e95;">
                                <th><input type="checkbox" id="checkAll"></th>
                                <th>机柜编号</th>
                                <th>机房</th>
                                <th>机架数量</th>
                                <th>创建时间</th>
                                <th>更新时间</th>
                            </tr>
                            {% for cabinet in cabinet_list %}
                            <tr>
                                <td><input type="checkbox" name="_dataCheckBox"></td>
                                <td><a href="/assets/cabinet/change/?cabinet_id={{ cabinet.id }}">{{ cabinet.name }}</a></td>
                                <td>{{ cabinet.idc.name }}</td>
                                <td>{{ cabinet.rack_set.select_related | rack_count:cabinet.id  }}</td>
                                <td>{{ cabinet.create_time }}</td>
                                <td>{{ cabinet.update_time }}</td>
                            </tr>
                            {% endfor %}
                        </thead>
                    </table>
                </div>
                <!-- /.panel-body -->
            </div>
        </div>
       <!-- /.col-lg-12 -->
    </div>
    <div class="col-sm-5 pull-left" id="action_buttons" style="font-size: 12px">
      <span id="selected_count">0</span>&nbsp;选择 &nbsp;
      <button class="btn btn-default btn-sm" disabled>启用</button>
      <button class="btn btn-default btn-sm" disabled>禁用</button>
      <button class="btn btn-default btn-sm" disabled>修改</button>
      <button class="btn btn-default btn-sm" disabled>删除</button>
    </div>
    <div class="pull-right" style="margin-right: 20px">
        {{ count }}&nbsp;机柜
    </div>
{% endblock %}


{% block js %}
    <script>
        function ChangeType(doc) {
            var idc = $(doc).val();
            location.href="/assets/cabinet/?idc="+idc;
            $(this).val(idc).attr("selected",true);
        }
        window.onload=function () {
            $("#idc-search").find("option[value='{{ idc_type }}']").attr("selected",true);
        }
    </script>
    <script>
        name='cabinet';
        function datatable(){
            $('#datatable').DataTable({
                "language": {
                    "lengthMenu": "每页 _MENU_ 条记录",
                    "zeroRecords": "没有找到记录",
                    "sInfo": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 ),显示第 _START_ 至 _END_ 项(总共 _TOTAL_ 项)",
                    "infoEmpty": "无记录",
                    "infoFiltered": "(从 _MAX_ 条记录过滤)",
                    "sSearch": "搜索:",
                    "oPaginate": {
                        "sFirst": "首页",
                        "sPrevious": "上一页",
                        "sNext": "下一页",
                        "sLast": "末页"
                    }
                }
            });
        };
/* list all data*/
    function list(){
        url = "/listapi?method="+name;
        $.getJSON(url,function(data){
           data=JSON.parse(data['result']); //object
           if (data['code']== 0){
               var str = '';
               $.each(data.result,function(k,v){
                   str +='<tr class="odd gradeX">'+
                   '<td>'+v['name']+'</td>'+
                   '<td>'+v['idc_name']+'</td>'+
                   '<td>'+v['power']+'</td>'+
                   '<td>'+
                   '<button class="btn btn-primary btn-sm update-btn" data-id="'+v['id']+'">更新</button>'+
                   '<button class="btn btn-danger btn-sm delete-btn" data-id="'+v['id']+'">删除</button>'+
                   '</td>'+ '</tr>'
               })
                    $("tbody").html(str)
                     datatable()
                }else{
                    swal("error", data['errmsg'],"error")
                }
             })
    }

list();

/*列出机房ids信息，并且拼接成复选框*/

    function idclist(){
        var url = "/listapi?method=idc"
        $.getJSON(url, function(data){
            data=JSON.parse(data['result'])
            console.log(data)
            if (data['code']== 0){
                var str = ''
                $.each(data.result, function(k,v){
                    str += '<option value="'+v['id']+'">'+v['idc_name']+'</option>'
                })
                $("#idc_id").html(str)
                $('#idc_id').multiselect({maxHeight:200, enableCaseInsensitiveFiltering: true})
                $("#idc_id").multiselect('refresh')
            }else{
                    swal("error","获取权限列表失败," + data['errmsg'],"error")
            } //if end
        })
    }

/*点击按钮，显示添加IDC模态窗*/
$("#addBtn").on('click',function(){
    idclist()
    $('#addModal').modal('show')
})
/*检查表单数据是否合法*/
$("#addForm").Validform({
    btnSubmit:"#submitbtn",
    tiptype:3,
    datatype:{
        "zh2-4" : /^[\u4E00-\u9FA5\uf900-\ufa2d]{2,4}$/,
    }
})
/*cabinet添加*/
$('#addForm').on('submit',function(){
        var str = $('#addForm').serialize()
        var data={'method':name,'formdata':str}
        $.post('/addapi',data,function(data){
            data=JSON.parse(data);   //将json串转换为对象，然后取值
            data = JSON.parse(data['result']) //object
            console.log(data)
            if (data['code']==0){
                    swal({
                        title:"success",
                        text:"添加IDC成功",
                        type:"success",
                        confirmButtonText:'确定'
                        },function(){
                            $('#addModal').modal('hide')
                            window.location.reload();
                         })
            }else{
                swal("error","创建IDC失败," + data['errmsg'],"error")
             }   /*if end*/
         })  /*post end*/
         return false;
})  /*submit end*/



/*修改用户密码*/
$("tbody").on('click','.passwd-btn',function(){
    var id = $(this).attr('data-id')
    $('#passwdid').val(id)
    $('#ChangePasswdModal').modal('show')
})
$('#ChangePasswdForm').on('submit',function(){
    var str = $('#ChangePasswdForm').serialize()
    var url = '/user/changepasswd'
    $.post(url,str,function(result){
        result = JSON.parse(result)
        if (result['code']==0){
            swal({
                title:"success",
                text:"密码更新成功",
                type:"success",
                confirmButtonText:'确定'
                },function(){
                    $('#ChangePasswdModal').modal('hide')
                })
        }else{
            $('#errorMsg').html('failed '+result['errmsg']).show()
        }
    })
    return false
})

/*点击按钮，显示IDC用户模态窗,并获取用户的信息*/
$("tbody").on('click','.update-btn',function(){
    var id = $(this).attr('data-id')
    var url = "/getapi?method="+name+"&id="+id
    $.getJSON(url,function(data){
      data = JSON.parse(data['result'])
      console.log(data)
      if (data['code']==0){
          $('#upid').val(data['result']['id'])
          $('#upname').val(data['result']['name'])
          $('#uppower').val(data['result']['power'])
	  upidclist()
          $('#updateModal').modal('show')
      }else{
          swal("Error", data['errmsg'], "error")
      }
    })
})

function upidclist(){
    var url = "/listapi?method=idc"
    $.getJSON(url, function(data){
        data=JSON.parse(data['result'])
        console.log(data)
        if (data['code']== 0){
            var str = ''
            $.each(data.result, function(k,v){
                str += '<option value="'+v['id']+'">'+v['idc_name']+'</option>'
            })
            $("#upidc_id").html(str)
            $('#upidc_id').multiselect({maxHeight:200, enableCaseInsensitiveFiltering: true})
            $("#upidc_id").multiselect('refresh')
        }else{
                swal("error","获取权限列表失败," + data['errmsg'],"error")
        } //if end
    })

}

/*检查表单数据是否合法*/
$("#updateForm").Validform({
    btnSubmit:"#upbtn",
    tiptype:3,
    datatype:{
        "zh2-4" : /^[\u4E00-\u9FA5\uf900-\ufa2d]{2,4}$/,
    }
})


/*更新cabinet信息*/
$('#updateForm').on('submit',function(){
        var str = $('#updateForm').serialize()
        var data = {'method':name,'formdata':str}
        $.post('/updateapi',data, function(data){  // data is string
            data = JSON.parse(data)    //object
            data = JSON.parse(data['result']) //object
            console.log(data)
            if (data['code']==0){
            swal({
                title:"success",
                text:"更新成功",
                type:"success",
                confirmButtonText:'确定'
                },function(){
                    $('#updateModal').modal('hide')
                    location.reload()
                })
            }else{
                $('#uperrorMsg').html('Failed: '+data['errmsg']).show()
            }
        })
            return false   //get data and end
})  //submit form

/*删除cabinet*/
$("tbody").on('click','.delete-btn',function(){
	if(confirm("是否确认删除？")){
		var id = $(this).attr('data-id')
		var url =  "/deleteapi?method="+name+"&id="+id
        console.log(url)
		$.getJSON(url,function(data){
            data = JSON.parse(data['result'])
			if (data['code']== 0 ){
                swal({
                    title:"success",
                    text:"删除成功",
                    type:"success",
                    confirmButtonText:'删除成功'
                    },function(){
                        location.reload()
                    })

			}else{
				swal(data['errmsg'])
			}
    	})
    }  // end confirm
})
    </script>
{% endblock %}